package com.stockz.train.spring.factory;

import java.util.Map;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.stereotype.Component;

import com.stockz.core.util.Global;
import com.stockz.train.domain.intf.TrainingMarker;
import com.stockz.train.util.TrainingConstant;

@Component
public class TrainingBeanFactoryPostProcessor implements
		BeanFactoryPostProcessor {

	@Override
	public void postProcessBeanFactory(ConfigurableListableBeanFactory factory)
			throws BeansException {
		Boolean isTrainingMode = (Boolean)Global.get(TrainingConstant.isTrainingMode);
		Map<String,TrainingMarker> beans = factory.getBeansOfType(TrainingMarker.class);
		for(TrainingMarker bean : beans.values()){
			Map<String,Object> otherMap = (Map<String,Object>)factory.getBeansOfType(bean.getClass().getSuperclass());
			for(String key : otherMap.keySet()){
				if(isTrainingMode != null && isTrainingMode){
					if(!TrainingMarker.class.isAssignableFrom(otherMap.get(key).getClass())){
						((BeanDefinitionRegistry) factory).removeBeanDefinition(key);
					}
				}else{
					if(TrainingMarker.class.isAssignableFrom(otherMap.get(key).getClass())){
						((BeanDefinitionRegistry) factory).removeBeanDefinition(key);
					}
				}
			}
		}
	
	}
	
}
